<template>
  <div class="ffu_total">
    <div v-loading="loading" class="chart-wrap">
      <div class="lf-wrap">
        <div class="black mg-bt-16">
          <modelTitle :title="'利用率总览'" />
          <px-table v-loading="tableLoading" :data="tableData" stripe size="small" border class="table-wrap">
            <px-table-column type="index" label="序号" fixed width="55" align="center" />
            <px-table-column prop="label" label="能源" min-width="120" show-overflow-tooltip />
            <px-table-column prop="supplyText" label="总供给量" min-width="80" show-overflow-tooltip />
            <px-table-column prop="consumptionText" label="终端用户消耗量" min-width="80" show-overflow-tooltip />
            <px-table-column prop="lossText" label="损失量" min-width="160" show-overflow-tooltip />
            <px-table-column prop="ratio" label="终端利用率" min-width="120" show-overflow-tooltip />
          </px-table>
        </div>
      </div>
      <div class="rt-wrap">
        <modelTitle :title="'利用率趋势'" />
        <btnImageAndData class="btn" @exportChange="val => handlerExport(val, 'lineChartRef')" />
        <div v-if="resData?.trend?.yaxis?.length" ref="lineChartRef" class="chart" />
        <px-empty v-else :image-size="50" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, computed, nextTick, getCurrentInstance } from "vue";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import { getViewEnergyUseRatioAPI } from "@/api/energy/flow";
import * as echarts from "echarts";
import btnImageAndData from "@/views/common/energy/components/btnImageAndData/index.vue";
const { proxy } = getCurrentInstance();
const props = defineProps({
  timeType: {
    type: String,
    default: ""
  },
  queryParams: {
    type: Object,
    default: () => {}
  }
});

const lineChartRef = ref(null);
let chartObj = {};

const state = reactive({
  loading: false,
  tableData: [],
  tableLoading: false,
  resData: {
    table: [],
    trend: {
      xaxis: [],
      yaxis: []
    }
  }
});
const { loading, tableData, tableLoading, resData } = toRefs(state);

const queryParams = computed(() => props.queryParams);

onMounted(() => {
  getTableLineData();
});

const getTableLineData = async () => {
  try {
    state.loading = true;
    const { startDate, endDate, dimension } = getParams();
    const params = {
      startDate,
      endDate,
      dimension
    };
    if (startDate && endDate) {
      const res = await getViewEnergyUseRatioAPI(params);
      if (Array.isArray(res?.table) && res?.table?.length) {
        res?.table?.forEach(i => {
          i.supplyText = i.supply + " " + i.measureUnit;
          i.consumptionText = i.consumption + " " + i.measureUnit;
          i.lossText = i.loss + " " + i.measureUnit;
        });
        state.tableData = res?.table;
      }
      nextTick(() => {
        chartObj.lineChartRef = res?.trend?.yaxis?.length ? drawLineChart(lineChartRef.value, res?.trend) : "";
      });
      state.resData = res;
    }
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

const drawLineChart = (dom, obj) => {
  const colors = ["#FD7C7C", "#3B82F6", "#13C2C2", "#FFC53D", "#FD7C7C", "#3B82F6", "#13C2C2", "#FFC53D"];
  let yAxisAry = [];
  let seenUnits = new Map(); // 用来进行去重
  let seriesData = [];
  obj?.yaxis?.forEach((i, idx) => {
    seriesData.push({
      name: i.name,
      type: "line",
      yAxisIndex: idx,
      data: i.value,
      unit: i.unit,
      tooltip: {
        valueFormatter: function (value) {
          if (value === null || value === undefined) {
            value = "-";
          }
          return value + " " + i.unit;
        }
      }
    });

    if (!seenUnits.has(i.unit)) {
      seenUnits.set(i.unit, true);
    }
  });
  [...seenUnits]?.forEach(([key, value], idx) => {
    yAxisAry.push({
      type: "value",
      name: key,
      alignTicks: true,
      axisLabel: {
        formatter: function (value) {
          if (value >= 1000000000) {
            return (value / 1000000000).toFixed(1) + "B"; // 十亿
          } else if (value >= 1000000) {
            return (value / 1000000).toFixed(1) + "M"; // 百万
          } else if (value >= 1000) {
            return (value / 1000).toFixed(1) + "K"; // 千
          }
          return value; // 原始值
        }
      },
      position: idx === 0 ? "left" : "right",
      offset: idx === 0 ? 0 : (idx - 1) * 60,
      axisLine: {
        show: true,
        lineStyle: {
          color: colors[idx]
        }
      }
    });
  });
  seriesData?.forEach(i => {
    const idx = yAxisAry?.findIndex(j => j.name === i.unit);
    i.yAxisIndex = idx;
  });
  let options = {
    color: colors,
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross"
      }
    },
    grid: {
      right: `${yAxisAry.length > 1 ? (yAxisAry.length - 1) * 10 : 10}%`,
      bottom: "10%"
    },
    // toolbox: {
    //   show: true,
    //   feature: {
    //     saveAsImage: {
    //       title: "点击保存为图片"
    //     }
    //   }
    // },
    legend: {
      type: "scroll"
    },
    xAxis: [
      {
        type: "category",
        axisTick: {
          alignWithLabel: true
        },
        data: obj?.xaxis || []
      }
    ],
    yAxis: yAxisAry,
    series: seriesData
  };
  if (dom) {
    let myChart = echarts.init(dom);
    myChart.clear();
    myChart.setOption(options);
    return myChart;
  }
};

// 导出方法
const handlerExport = (val1, val2) => {
  if (val1 === "data") {
    const dimensionMap = {
      Hourly: "H",
      Daily: "D",
      Monthly: "M",
      Yearly: "Y"
    };
    const params = {
      dimension: dimensionMap[queryParams.value.queryTimeGranularity],
      startDate: queryParams.value.startTime,
      endDate: queryParams.value.endTime,
      factoryId: "",
      facCode: "",
      hseAreaCode: []
    };
    proxy.download("post", "/energy/balance/energyUseRatioLossExport", params, "利用率-损失曲线.xlsx");
  } else {
    let myChart = chartObj[val2];
    if (!myChart) return;
    // 获取Base64图片数据
    const imgUrl = myChart.getDataURL({
      type: "png",
      pixelRatio: 2,
      backgroundColor: "#fff"
    });
    // 创建并触发下载链接
    const link = document.createElement("a");
    link.href = imgUrl;
    link.download = "chart.png";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
};
// 获取参数
const getParams = () => {
  let timeType = queryParams.value.queryTimeGranularity;
  let startDate = queryParams.value.startTime || "";
  let endDate = queryParams.value.endTime || "";

  let timeObj = {
    Hourly: "H",
    Daily: "D",
    Monthly: "M",
    Yearly: "Y"
  };
  let dimension = timeObj[timeType] || "M";
  return {
    startDate,
    endDate,
    dimension
  };
};
const getData = () => {
  getTableLineData();
};
defineExpose({
  getData
});
</script>

<style lang="scss" scoped>
.ffu_total {
  position: relative;
  display: flex;
  flex: 1;

  .iframe-con {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    overflow: hidden !important;
    border: 0;
  }

  .mg-bt-16 {
    margin-bottom: 16px;
  }

  .chart-wrap {
    display: flex;
    flex: 1;
    flex-direction: column;

    .lf-wrap {
      display: flex;
      flex: 1;
      flex-direction: column;

      .black {
        position: relative;
        display: flex;
        flex: 1;
        flex-direction: column;
        padding: 16px 24px;
        background: #fff;
        border-radius: 4px;

        .table-wrap {
          flex: 1;
          margin-top: 16px;
        }
      }
    }

    .rt-wrap {
      position: relative;
      display: flex;
      flex: 1;
      flex-direction: column;
      padding: 16px 24px;
      background: #fff;
      border-radius: 4px;

      .chart {
        flex: 1;
        margin-top: 26px;
      }
    }

    .btn {
      position: absolute;
      top: 16px;
      right: 24px;
    }
  }
}
</style>
